<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add()">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(item, index)">编辑</button>
          </td>
        </tr>
        <tr v-if="arr.length ? false : true">
          <td colspan="5" class="zxc">还没有数据，添加一些吧~</td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr: [
        { name: "小明", age: 18, gender: "男" },
        { name: "小红", age: 20, gender: "女" },
        { name: "小王", age: 21, gender: "女" },
        { name: "小张", age: 19, gender: "男" },
      ],
      name: "",
      age: "",
      gender: "",
      id: "",
    };
  },
  methods: {
    add() {
      const obj = {
        name: this.name,
        age: this.age,
        gender: this.gender,
      };
      if (this.gender === "" || this.name === "" || this.age === "")
        return alert("输入不能为空");
      if (this.id === "") {
        this.id = this.arr.length + 1;
      }
      this.arr.splice(this.id, 1, obj);
      this.name = "";
      this.age = "";
      this.gender = "";
      this.id = "";
    },
    del(index) {
      this.arr.splice(index, 1);
    },
    edit(item, index) {
      this.name = item.name;
      this.age = item.age;
      this.gender = item.gender;
      this.id = index;
    },
  },
};
</script>
<style scoped>
.zxc {
  /* border-collapse: collapse;
   */
  text-align: center;
  color: red;
  /* width: 100%; */
}
</style>
